﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService

Partial Class Control_Menu_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Request("MenuId") = "" Or Request("MenuId") = "0" Then
                lbtnUpOneLevel.Enabled = False
            End If
            BindToGrid()
            If HasPermission(Function_Name.Menu, Session("RoleID"), 0, Audit_Type.Delete) = True Then
                btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
            Else
                btnDelete.Enabled = False
            End If
        End If
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strSearch As String = "")
        Dim data As New VSEntities
        'So ban ghi muon the hien tren trang
        Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
        Dim curMenuId As Integer = IIf(Request("MenuId") = "", 0, Request("MenuId"))
        Dim _lang As Integer = Session("LanguageId")
        Dim p = (From q In data.Menus Where q.ParentId = curMenuId And q.LanguageId = _lang Order By q.Sort Ascending Select q).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
        Dim strKey_Name() As String = {"MenuId", "Title", "ParentId", "StatusId"}
        'Tong so ban ghi
        hidCount.Value = p.Count()
        Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
        With grdShow
            .DataKeyNames = strKey_Name
            .DataSource = p
            .DataBind()
        End With
        lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        BindToGrid(lnkTile.ToolTip)
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub chkAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        For Each itm As GridViewRow In grdShow.Rows
            Dim chkItem As CheckBox = CType(itm.Cells(0).FindControl("chkItem"), CheckBox)
            If chkItem.Enabled = True Then
                chkItem.Checked = CType(sender, CheckBox).Checked
            End If
        Next
    End Sub
    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Dim data As New VSEntities
        intId = grdShow.DataKeys(hidID.Value)("MenuId").ToString
        Dim q = (From p In data.Menus Where p.MenuId = intId Select p).FirstOrDefault
        Try
            data.Menus.DeleteObject(q)
            data.SaveChanges()
            Insert_App_Log("Del Menu:" & q.Title & "", Function_Name.Menu, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
            Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()

            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
        End Try
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Dim data As New VSEntities
        Try
            For Each item As GridViewRow In grdShow.Rows
                Dim chkItem As New CheckBox
                chkItem = CType(item.FindControl("chkItem"), CheckBox)
                If chkItem.Checked Then
                    intTotal += 1
                    intId = grdShow.DataKeys(item.RowIndex)("MenuId").ToString
                    Dim q = (From p In data.Menus Where p.MenuId = intId Select p).FirstOrDefault
                    Try
                        data.Menus.DeleteObject(q)
                        data.SaveChanges()
                        intCount += 1
                        Insert_App_Log("Del Menu:" & q.Title & "", Function_Name.Menu, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Catch ex As Exception
                    End Try
                End If
            Next
            If intCount > 0 Then
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
            Else
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End If
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()

            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
        End Try
        BindToGrid()
    End Sub
    Protected Sub grdShow_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdShow.PageIndexChanging
        grdShow.PageIndex = e.NewPageIndex
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim status As Integer = grdShow.DataKeys(e.Row.RowIndex)("StatusId")
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            Dim chkItem As CheckBox = CType(e.Row.FindControl("chkItem"), CheckBox)
            'Permission
            If HasPermission(Function_Name.Menu, Session("RoleID"), 0, Audit_Type.Delete) = True Then
                lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Else
                lnkbtnDelete.Enabled = False
                chkItem.Enabled = False
            End If

            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            hplEdit.NavigateUrl = "../../Page/Menu/Edit.aspx?MenuId=" & grdShow.DataKeys(e.Row.RowIndex)("MenuId").ToString
            'Permission
            hplEdit.Enabled = HasPermission(Function_Name.Menu, Session("RoleID"), 0, Audit_Type.Edit)

            Dim hplTitle As HyperLink = CType(e.Row.FindControl("hplTitle"), HyperLink)
            hplTitle.NavigateUrl = "../../Page/Menu/List.aspx?MenuId=" & grdShow.DataKeys(e.Row.RowIndex)("MenuId").ToString
            hplTitle.Text = grdShow.DataKeys(e.Row.RowIndex)("Title").ToString
            'Permission
            hplTitle.Enabled = HasPermission(Function_Name.Menu, Session("RoleID"), 0, Audit_Type.ViewContent)
            Dim imbtnAsc As ImageButton = CType(e.Row.FindControl("imbtnAsc"), ImageButton)
            If e.Row.RowIndex = 0 Then
                imbtnAsc.Enabled = False
            Else
                imbtnAsc.Enabled = True
                imbtnAsc.Attributes.Add("onclick", "return SetID('" + e.Row.RowIndex.ToString + "');")
            End If

            Dim imbtnDesc As ImageButton = CType(e.Row.FindControl("imbtnDesc"), ImageButton)
            If e.Row.RowIndex = (hidCount.Value - 1) Then
                imbtnDesc.Enabled = False
            Else
                imbtnDesc.Enabled = True
                imbtnDesc.Attributes.Add("onclick", "return SetID('" + e.Row.RowIndex.ToString + "');")
            End If
        End If
    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        BindToGrid(1)
    End Sub
    Protected Sub lbtnUpOneLevel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbtnUpOneLevel.Click
        Dim MenuId = Request("MenuId")
        If MenuId = "" Or MenuId = "0" Then
            Response.Redirect("../../Page/Menu/List.aspx")
        Else
            Using data As New VSEntities
                Dim p = (From q In data.Menus Where q.MenuId = MenuId Select q.ParentId).FirstOrDefault
                Response.Redirect("../../Page/Menu/List.aspx?MenuId=" & p)
            End Using
        End If
    End Sub
    Protected Sub lbtnUpLevel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Using data As New VSEntities
            Dim intRowID As Integer = grdShow.DataKeys(CInt(rowID.Value))("MenuId")
            Dim lastRowID As Integer = grdShow.DataKeys(CInt(rowID.Value) - 1)("MenuId")
            Dim p = (From q In data.Menus Where q.MenuId = intRowID Select q).FirstOrDefault
            Dim t = (From q In data.Menus Where q.MenuId = lastRowID Select q).FirstOrDefault
            intRowID = p.Sort
            lastRowID = t.Sort
            p.Sort = lastRowID
            t.Sort = intRowID
            data.SaveChanges()

        End Using
        BindToGrid()
    End Sub
    Protected Sub lbtnDownLevel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Using data As New VSEntities
            Dim intRowID As Integer = grdShow.DataKeys(CInt(rowID.Value))("MenuId")
            Dim lastRowID As Integer = grdShow.DataKeys(CInt(rowID.Value) + 1)("MenuId")
            Dim p = (From q In data.Menus Where q.MenuId = intRowID Select q).FirstOrDefault
            Dim t = (From q In data.Menus Where q.MenuId = lastRowID Select q).FirstOrDefault
            intRowID = p.Sort
            lastRowID = t.Sort
            p.Sort = lastRowID
            t.Sort = intRowID
            data.SaveChanges()
        End Using
        BindToGrid()
    End Sub
#End Region
End Class
